﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Models.PDA;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.IdentityModel.Logging;
using NetTaste;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.XWPF.UserModel;
using Org.BouncyCastle.Asn1.X509;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using static NPOI.HSSF.Util.HSSFColor;

namespace DFGK_WMS.Repository
{
    internal class TOutboundOrderDetailRepository : BaseRepository<TShippingOrderDetail>, ITOutboundOrderDetailRepository
    {
        ITShippingOrderDetailRepository _tShippingOrderDetailRepository;

        public TOutboundOrderDetailRepository(DFGK_DB context, IMapper mapper, ITShippingOrderDetailRepository tShippingOrderDetailRepository) : base(context, mapper)
        {
            _tShippingOrderDetailRepository = tShippingOrderDetailRepository;
        }

        #region 基础接口

        /// <summary>
        /// PDA出库反填
        /// </summary>
        /// <param name="MaterialId"></param>
        /// <returns></returns>
        public bool PDAAddShippingOrderDetail(int MaterialId)
        {
            //if (MaterialId <= 0 )
            //{
            //    return false;
            //}
            //var TMateriallist = Context.TMaterial.FirstOrDefault(x => x.Id == MaterialId);

            //GroupShippingOrderDto groupShippingOrderDto = new GroupShippingOrderDto();
            //ChildShippingOrder childShippingOrder = new ChildShippingOrder();

            //childShippingOrder.MaterialId = MaterialId;
            //childShippingOrder.Name = TMateriallist.Name;
            //childShippingOrder.MakerialCategoryId = TMateriallist.MaterialCategoryId;
            //childShippingOrder.MaterialCategoryName = TMateriallist.MaterialCategoryName;
            //childShippingOrder.Code = TMateriallist.Code;
            //childShippingOrder.ModelSpec = TMateriallist.ModelSpec;
            //childShippingOrder.QualityState = TMateriallist.QualityState;
            //childShippingOrder.Measurement = TMateriallist.UnitName;
            //var TInventorylist = Context.TInventories.FirstOrDefault(x => x.MaterialCode == childShippingOrder.Code);
            //childShippingOrder.Position = TInventorylist.LocationCode;
            //childShippingOrder.Price = TMateriallist.Price;
            //childShippingOrder.TcellId = TInventorylist.LocationId;
            //childShippingOrder.TcellCode = TInventorylist.LocationCode;
            //childShippingOrder.TcellName = TInventorylist.LocationName;

            //groupShippingOrderDto.childShippingOrders.Add(childShippingOrder);

            //TShippingOrderDetail tShippingOrderDetail = new TShippingOrderDetail
            //{
            //    //MaterialId = MaterialId,
            //    //MaterialName = TMateriallist.Name,
            //    //MaterialCategoryId = TMateriallist.MaterialCategoryId,
            //    //MaterialCategoryName = TMateriallist.MaterialCategoryName,
            //    //MaterialCode = TMateriallist.Code,
            //    //ModelSpec = TMateriallist.ModelSpec,
            //    //QualityState = TMateriallist.QualityState,
            //    //UnitName = TMateriallist.UnitName,
            //    CreateDate = DateTime.Now,
            //};

            //// 初始化InventoryList和LockCell列表
            //tShippingOrderDetail.InventoryList = new List<TInventory>();
            //tShippingOrderDetail.LockCell = new List<TShippingLockCell>();

            //// 设置tShippingOrderDetail的其他属性
            //tShippingOrderDetail.InventoryList.Add(new TInventory { Price = TMateriallist.Price });
            //tShippingOrderDetail.LockCell.Add(new TShippingLockCell
            //{
            //    CellId = TInventorylist.LocationId,
            //    CellCode = TInventorylist.LocationCode,
            //    CellName = TInventorylist.LocationName
            //});

            //// 将tShippingOrderDetail对象添加到TShippingOrderDetails集合中
            //Context.TShippingOrderDetails.Add(tShippingOrderDetail);

            //// 保存更改到数据库中
            //return Context.SaveChanges() > 0;
            return false;
        }



        // 获取出库单列表
        public List<TShippingOrderDetail> GetShippingOrder()
        {
            var list = Context.TShippingOrderDetails.ToList();

            return list;
        }

        /// <summary>
        /// 获取出库单明细表数据
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public TShippingOrderDetail GetShippingOrderDetail(int OrderId)
        {
            var list = Context.TShippingOrderDetails        
                .Where(x => x.Id == OrderId)
                .FirstOrDefault();

            return list;

        }

        // 查询出库单明细表
        public TShippingOrderDetail GetShippingOrderDetail(string OrderSN)
        {
            var list = Context.TShippingOrderDetails
                .Where(x => x.OrderSn == OrderSN)
                .FirstOrDefault();

            return list;
        }     

        /// <summary>
        /// 根据库存表修改仓位状态
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool UpdateFullStatus(string LocationCode)
        {
            var TInventories = Context.TInventories;
            var firstInventory = TInventories.FirstOrDefault(p => p.LocationCode == LocationCode);

            if (firstInventory == null)
            {
                return false;
            }
            var TCell = Context.TCells.FirstOrDefault(p => p.Code == firstInventory.LocationCode);
            if (TCell == null)
            {
                return false;
            }
            var Status = TCell.Status;
            if (Status == 1)
            {
                Status = 2;
                Context.SaveChanges();
            }
            else
            {
                return false;
            }
            return true;

        }


        /// <summary>
        ///  修改库区状态
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool UpdateAreasStatus(string AreaCode)
        {
            //var TInventories = Context.TInventories;
            //var firstInventory = TInventories.FirstOrDefault(p => p.AreaCode == AreaCode);

            //if (firstInventory == null)
            //{
            //    return false;
            //}        
           
            return true;
        }

        /// <summary>
        /// 库存表删除数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DelTInventoriesById(int id)
        {
            try
            {
                var delTinventories = Context.TInventories.Where(p => p.Id == id).ToList();
                if (delTinventories.Any())
                {
                    Context.RemoveRange(delTinventories);
                    Context.SaveChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }

        /// <summary>
        /// 出库单明细添加信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool AddTShippingOrderDetails(TShippingOrderDetail item)
        {         
            //库房信息
            var warehouseobj = Context.TWarehouses.Find(item.WarehouseId);
            if (warehouseobj != null)
            {
                //item.WarehouseName = warehouseobj.Name;
                //item.WarehouseCode = warehouseobj.Code;
            }          
            //供应商信息
            var supplierobj = Context.TSuppliers.Find(item.SupplierId);
            if (supplierobj != null)
            {
                item.SupplierName = supplierobj.Name;
            }
            ////物料信息
            //var materialobj = Context.TMaterials.Find(item.MaterialId);
            //if (materialobj != null)
            //{
            //    item.MaterialCode = materialobj.Code;
            //    item.MaterialName = materialobj.Name;
            //    item.UnitId = materialobj.UnitId;
            //    item.UnitName = materialobj.UnitName;
            //}
                     
            ////物料凭证
            //var materialkeyobj = Context.TMaterialKeys.Find(item.MaterialId);
            //if (materialkeyobj != null)
            //{
            //    item.Mblnr = materialkeyobj.Mblnr;
            //    item.Mjahr = materialkeyobj.Mjahr;
            //    item.Zeile = materialkeyobj.Zeile;
            //    item.PurOrderNo = materialkeyobj.PurOrderNo;
            //    item.PurOrderLineNo = materialkeyobj.PurOrderLineNo;
            //    item.PurOrderLineType = materialkeyobj.PurOrderLineType;
            //    item.ProOrderNo = materialkeyobj.ProOrderNo;
            //}

            ////包装数量
            //item.PackQty = 0;
       
            ////已经下架的数量
            //item.PickedQty = 0;
            ////已经出库完成的数量
            //item.ShippedQty = 0;
           
            //合同编号
            item.ContractNo = "";
            //是否多托盘
            
            //是否挂起
            item.IsSuspend = true;
            //是否出库核审
            item.IsOutOrderReview = true;
            //是否一次出库
            item.IsOnceOut = true;
            //生成厂家
            item.ProduceFactory = "";


            //订单来源默认手动创建
            item.SourceType = 0;
            //物料类型编码
            //item.MaterialTypeCode = "EndProduct";
            ////质检状态默认为合格
            //item.QualityState = 1;
            ////质量状态
            //item.Status = 0;
            //item.PackQty = 0;
            //item.Qty = item.Qty;
            #region 审计字段
            item.CreateUserId = item.NowUserId;
            item.CreateUserName = item.NowUserRealName;
            item.CreateDate = DateTime.Now;
            item.ModifyUserId = item.NowUserId;
            item.ModifyUserName = item.NowUserRealName;
            item.ModifyDate = DateTime.Now;
            item.AuditUserId = item.NowUserId;
            item.AuditUserName = item.NowUserRealName;
            item.AuditDate = DateTime.Now;
            item.SubmitUserId = item.NowUserId;
            item.SubmitUserName = item.NowUserRealName;
            item.SubmitDate = DateTime.Now;
            #endregion
            //采购订单行项目类型
            item.PurOrderLineType = 0;

            Context.TShippingOrderDetails.Add(item);
            return Context.SaveChanges() > 0;
        }



        /// <summary>
        /// 获取出库单明细
        /// </summary>
        /// <returns></returns>
        public List<TShippingOrderDetail> GetTShippingOrderDetail(int pageIndex, int pageSize)
        {

            var list = Context.TShippingOrderDetails
                .Where(x => x.Status == 3)
                .OrderBy(x => x.CreateDate)
                .AsEnumerable()
                .GroupBy(x => x.OrderSn)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .SelectMany(x => x);
            return list.ToList();
        }

        public string GetCellCodeByRFIDCode(string rfidCode)
        {
            string cellCode = "";

            var cellCodeModel = Context.TPriceTags.Where(x => x.PriceTagsUrl == rfidCode);
            if(cellCodeModel.Count() <= 0)
            {
                return null;
            }
            cellCode = cellCodeModel.FirstOrDefault().CellCode;

            return cellCode;
        }
        /// <summary>
        /// 获取出库单明细  多个物料版本
        /// </summary>
        /// <returns></returns>
        public List<TShippingOrderDetailPlusDTOGroup> GetTShippingOrderDetailPlus(int pageIndex, int pageSize)
        {
            var list = Context.TShippingOrderDetails.AsEnumerable().Where(s=>s.Status==0).OrderByDescending(s=>s.CreateDate).Skip((pageIndex - 1) * pageSize).Take(pageSize).GroupBy(s=>s.OrderSn);
            List<TShippingOrderDetailPlusDTOGroup> resList = new List<TShippingOrderDetailPlusDTOGroup>();
            foreach (var item in list)
            {
                var key = item.Key;
                var lockCellList = new List<TShippingLockCell>();
                foreach (var value in item)
                {
                    var lockCell = Context.TShippingLockCells.Where(s=>s.OrderDetailId==value.Id && s.IsPicking==false).ToList();
                    if (lockCell != null && lockCell.Count() > 0)
                    {
                        foreach (var item1 in lockCell)
                        {
                            lockCellList.Add(item1);
                        }
                    } 
                }
                if (lockCellList != null && lockCellList.Count() > 0)
                {
                    resList.Add(new TShippingOrderDetailPlusDTOGroup(key, lockCellList));
                }
            }
            return resList;

        }

        /// <summary>
        /// 根据ID获取出库单详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TShippingOrderDetail  GetTShippingOrderDetailById(int id)
        {
            List<TShippingOrderDetail> item = new List<TShippingOrderDetail>();

            var list = Context.TShippingOrderDetails.FirstOrDefault(x => x.Id == id);
            var fileList = Context.TShppingOrderDetailFile.Where(x => x.ShippingOrderSn == list.OrderSn);
            List<FileClass> files = new List<FileClass>();
            foreach (var item1 in fileList)
            {
                FileClass file = new FileClass();
                file.name = item1.FileName;
                file.url = item1.FileUrl;
                files.Add(file);
            }
            list.FileUrl = files;

            return list;
        }

        /// <summary>
        /// 根据物料查询库存数量
        /// </summary>
        /// <param name="MaterialsId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public decimal? GetInventoryQty(decimal? MaterialsId)
        {
            if (MaterialsId == null)
            {
                return null;
            }

            decimal? num = Context.TInventories
                .Where(x => x.MaterialId == MaterialsId)
                .Sum(x => x.AvailableQty);

            return num;
        }

        /// <summary>
        /// 根据物料Id查询是否存在此物料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TMaterial> GetMaterial(int id)
        {
            var list = Context.TMaterial
                .Where(x => x.Id == id)
                .ToList();
            return list;
        }

        /// <summary>
        /// 根据库存Id查询库存表中是否存在这条数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int GetInventory(int id)
        {
            var list = Context.TInventory
                .Where(x => x.Id == id);
            if (list.Count() > 0)
            {
                return list.Count();
            }
            else
            {
                return 0;
            }

        }

        // 根据托盘条码号查询库存表
        public TInventory GetInventory(string PalletBarcode)
        {
            var list = Context.TInventories
                .FirstOrDefault(x => x.PalletBarcode == PalletBarcode);

            if (list == null)
            {
                return null;
            }
            return list;
        }

        /// <summary>
        /// 根据垛条码查询垛主
        /// </summary>
        /// <param name="PalletBarcode"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TStackingStorage> GetStackingStacker(string[] PalletBarcode)
        {
            var list = new List<TStackingStorage>();
            foreach (var item in PalletBarcode)
            {
                list.AddRange(Context.TStackingStorages.Where(x => x.PalletBarcode == item).ToList());
            }
            return list;
        }

        /// <summary>
        /// 根据垛条码查询物料
        /// </summary>
        /// <param name="PalletBarcode"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TInventory> GetMaterial(string PalletBarcode)
        {
            var list = Context.TInventories
                .Where(x => x.PalletBarcode.Equals(PalletBarcode)).ToList();

            return list;
        }

        /// <summary>
        /// 根据物料查询垛条码
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TInventory> GetStackingBarcode(int mid)
        {
            var list = Context.TInventory
                .Where(x => x.MaterialId == mid).ToList();

            return list;
        }

        /// <summary>
        /// 根据垛条码删除入库垛信息表中数据
        /// </summary>
        /// <param name="PalletBarcode"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelStackingStorages(string PalletBarcode)
        {
            try
            {
                var delTinventories = Context.TStackingStorages.Where(p => p.PalletBarcode == PalletBarcode).ToList();
                if (delTinventories.Any())
                {
                    Context.RemoveRange(delTinventories);
                    Context.SaveChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 往库存流水表中插入数据
        /// </summary>
        /// <param name="inventoryLog"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool CreateInventoryFlow(TInventoryLog item)
        {
            // 来源单号
            var itmeid = Context.TInventoryAdjusts.Find(item.Id);
            if (itmeid != null)
            {
                item.SourceSn = itmeid.SourceSn;
                item.CreateDate = DateTime.Now;
                item.CreateUserId = itmeid.NowUserId;
                item.CreateUser = itmeid.NowUserRealName;

            }
            // 仓库信息
            var warehouse = Context.TWarehouses.Find(item.WarehouseId);
            if (warehouse != null)
            {
                item.WarehouseName = warehouse.Name;
            }               
            // 物料信息
            var material = Context.TMaterials.Find(item.MaterialId);
            if (material != null)
            {
                item.MaterialName = material.Name;
                item.MaterialCode = material.Code;
            }
            // 数量信息
            var qty = Context.TInventory.AsQueryable();
            if (qty != null)
            {
                var filteredQty = qty.Where(x => x.MaterialCode == item.MaterialCode && x.AvailableQty > 0)
                                     .Select(x => x.AvailableQty);
                // 原始数量
                item.StartQty = filteredQty.FirstOrDefault();
                // 出库数量

                // 最终数量

            }
            // 单位信息
            var baseUnit = Context.TInventory.AsQueryable()
                .Where(x => x.UnitId == item.BaseUnitId)
                .Select(x => x.UnitName)
                .FirstOrDefault();
            if (baseUnit != null)
            {
                item.BaseUnitName = baseUnit;
            }


            // 备注
            item.Remark = "";
            // 批次号
            item.BatchNo = "";
            // 来源单据类型
            item.SourceType = 2;
            // 托盘号
            item.PalletBarcode = "";

            Context.Add(item);
            Context.SaveChanges();


            return true;

        }

        /// <summary>
        /// 首次提交，更新库存中状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int UpdStatus(int id)
        {
            int count = 0;
            var inventory = Context.TInventory.FirstOrDefault(x => x.MaterialId == id);
            if (inventory != null)
            {
                inventory.Status = 4;

                inventory.IsLock = inventory.IsLock.HasValue ? (bool)inventory.IsLock : false;

                count = count += 1;

                // 提交对数据库的更改
                Context.SaveChanges();
            }
            else
            {
                return 0;
            }
            return count;
        }

        /// <summary>
        /// 获取库存中当前这条数据的状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int GetStatus(int id)
        {
            var status = Context.TInventory.AsQueryable()
                .Where(x => x.Id == id)
                .Select(x => x.Status)
                .FirstOrDefault();
            return status ?? 0;

        }

        /// <summary>
        /// 根据ID查询入库垛信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TStackingStorage> GetStackingStorages(string[] PalletBarcode)
        {
            var list = new List<TStackingStorage>();
            foreach (var item in PalletBarcode)
            {
                var staSto = Context.TStackingStorages.Where(x => x.PalletBarcode == item);
                if (staSto != null)
                {
                    list.AddRange(staSto);
                }
            }
            return list.ToList();
        }

        /// <summary>
        /// 根据出库单号获取出库单明细
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        public List<TShippingOrderDetail> GetDeliveryOrderDetails(string OrderSn)
        {
            var list = Context.TShippingOrderDetails
                .Where(x => x.OrderSn == OrderSn)
                .ToList();

            return list;
        }

        /// <summary>
        /// 拣选出库
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPickingOutbound(TPickingStationDatum item)
        {
            TPickingStationDatum pickingStationDatum = new TPickingStationDatum();
            pickingStationDatum.child = new List<TPickingStationDataDetail>();

            var addedItem = Context.TPickingStationData.Add(item);
            Context.SaveChanges();

            if (addedItem != null)
            {
                int newPickingStationDataId = addedItem.Entity.Id;

                TPickingStationDataDetail pickingStationDataDetail = new TPickingStationDataDetail();
                pickingStationDataDetail.PickingStationDataId = newPickingStationDataId;

                pickingStationDataDetail.PickingStationDataId = newPickingStationDataId;
                pickingStationDataDetail.StationId = item.child[0].StationId;
                pickingStationDataDetail.StationCode = item.child[0].StationCode;
                pickingStationDataDetail.PackageBarcode = item.child[0].PackageBarcode;
                pickingStationDataDetail.Barcode = item.child[0].Barcode;
                pickingStationDataDetail.SkuNum = item.child[0].SkuNum;
                pickingStationDataDetail.IsSku = item.child[0].IsSku;
                pickingStationDataDetail.IsSelected = item.child[0].IsSelected;
                pickingStationDataDetail.PickedNum = item.child[0].PickedNum;
                pickingStationDataDetail.BarcodeRange = item.child[0].BarcodeRange;

                Context.TPickingStationDataDetails.Add(pickingStationDataDetail);

                // 再次保存以关联TPickingStationData和TPickingStationDataDetail之间的关系
                Context.SaveChanges();

                return true;
            }

            return false;
        }


        /// <summary>
        /// 获取拣选出库
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TPickingStationDatum> GetPickingStationDatum(int id)
        {
            var list = Context.TPickingStationData
                .Where(x => x.Id == id);

            return list.ToList();
        }

        /// <summary>
        /// 获取拣选出库详情
        /// </summary>
        /// <param name="PickingStationDataId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TPickingStationDataDetail> GetPickingStationDetail(int PickingStationDataId)
        {
            var list = Context.TPickingStationDataDetails
                .Where(x => x.PickingStationDataId == PickingStationDataId);

            return list.ToList();
        }

        /// <summary>
        /// 获取库存数量
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public decimal GetInventoryQuantity(int? MaterialId)
        {
            var Qty = Context.TInventories
                .Where(x => x.MaterialId == MaterialId)
                .Select(x => x.AvailableQty).Sum();
            if (Qty > 0)
            {
                return Qty.Value;
            }
            return 0;
        }

        /// <summary>
        /// 减去库存数量并修改库存状态
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool GetDwindleNumbers(TInventory upd, decimal? num)
        {
            if (upd == null)
            {
                return false;
            }
            upd.AvailableQty = upd.AvailableQty - num;
            upd.Status = 1;

            Context.SaveChanges();

            return true;

        }


        /// <summary>
        /// 往库存流水表添加数据
        /// </summary>
        /// <param name="OrderDTO"></param>
        /// <returns></returns>
        public bool AddInventoryFlow(SubmitOutListDTO OrderDTO)
        {
            try
            {
                if (OrderDTO == null)
                {
                    return false;
                }
                //// 往库存流水表插入数据
                //var materialId = OrderDTO.MaterialsId;
                //var warehouseId = OrderDTO.WareHouseId;
                //var areaCode = OrderDTO.AreaCode;

                //// 获取仓库和区域信息
                //var warehouse = Context.TWarehouses.FirstOrDefault(x => x.Id == warehouseId);
                //var area = Context.TAreas.FirstOrDefault(x => x.Code == areaCode);

                //// 获取物料信息
                //var material = Context.TMaterial.FirstOrDefault(x => x.Id == materialId);

                //// 获取货位、批次号、货主名称等信息
                //var inventory = Context.TInventory.FirstOrDefault(x => x.MaterialId == materialId);
                //var locationCode = inventory?.LocationCode;
                //var palletBarcode = inventory?.PalletBarcode;
                //var ownerId = inventory?.OwnerId;
                //var ownerName = inventory?.OwnerName;
                //var batchNo = inventory?.BatchNo;

                //// 获取单位转换信息
                //var unitConvert = Context.TUnitConvertFigres.FirstOrDefault(x => x.MaterialId == materialId);

                //// 计算开始数量和结束数量
                //var startQty = GetInventoryQuantity(materialId);
                //var endQty = startQty - OrderDTO.Qty;


                var lockCellList = Context.TShippingLockCells.Where(s => s.PalletBarcode.Equals( OrderDTO.palletBarcode)).ToList();
                var inventoryLogList = new List<TInventoryLog>();
                foreach (var item in lockCellList)
                {
                    var orderDet = Context.TShippingOrderDetails.Find(item.OrderDetailId);
                    var inv = Context.TInventory.Find(item.InventoryId);
                    // 创建 TInventoryLog 对象，并设置属性值
                    var inventoryLog = new TInventoryLog
                    {
                        SourceType = 1,
                        SourceSn = orderDet?.OrderSn,
                        WarehouseId = orderDet?.WarehouseId,
                        //WarehouseName = orderDet?.WarehouseName,
                        LocationCode = item.CellCode,
                        PalletBarcode = item.PalletBarcode,

                        MaterialId = item.MaterialId,
                        MaterialCode = item.MaterialCode,
                        MaterialName = item.MaterialName,
                        StartQty = item.InventoryQty,
                        ChangeQty = OrderDTO.qty,
                        EndQty = item.InventoryQty - OrderDTO.qty, //使用库存数量减去实际出库数量 等于最终数量
                        BaseUnitId = inv?.UnitId,
                        BaseUnitName = inv?.UnitName,
                        Remark = "",
                        CreateDate = DateTime.Now,
                        CreateUserId = OrderDTO.createUserld,
                        CreateUser = OrderDTO.createUser
                    };
                    inventoryLogList.Add(inventoryLog);
                }


                // 将 TInventoryLog 对象添加到数据库并保存更改
                Context.TInventoryLogs.AddRange(inventoryLogList);
                Context.SaveChanges();

                return true;
            }
            catch
            {
                throw;
            }

        }

        /// <summary>
        /// 查询指令记录
        /// </summary>
        /// <param name="criteria"></param>
        /// <param name="shippingOrderDetail"></param>
        /// <returns></returns>
        public List<TInstruct> GetInstructsCount(InstructCriteriaModel criteria, TShippingOrderDetail shippingOrderDetail)
        {
            var list = Context.TInstructs.AsQueryable();

            list = list.Where(t => t.InstructType == 2 && t.Status == 2);

            return list.ToList();
        }


        /// <summary>
        /// 查询定时任务
        /// </summary>
        /// <param name="RecordId"></param>
        /// <returns></returns>
        public bool ValidScheduledTaskData(int RecordId)
        {
            var list = Context.TScheduledTasks
                .Where(x => x.RecordId == RecordId && x.RecordType == 2);

            if (list == null)
            {
                return false;
            }

            return true;
        }

        // 插入日志
        public int InsertLog(TLog log)
        {
            try
            {
                Context.TLogs.Add(log);
                Context.SaveChanges();
                return 1;
            }
            catch
            {
                return -1;
            }
        }

        // 更新计划任务
        public int InsertScheduledTask(TScheduledTask item)
        {
            try
            {
                Context.TScheduledTasks.Add(item);

                return Context.SaveChanges();
            }
            catch { return -1; }
        }

        // 根据ID获取

        // 根据单号查询出库单明细数据并修改状态
        public bool UpdateShippingOrderDetail(int id)
        {
            var list = Context.TShippingOrderDetails
                .Where(x => x.Id == id)
                .FirstOrDefault();
            if (list == null)
            {
                return false;
            }
            list.IsOutOrderReview = false;

            return true;

        }

        // 更新库房信息
        public bool UpdInstructsCount(TShippingOrderDetail shippingOrderDetail)
        {
            var list = Context.TInstructs.FirstOrDefault();
            //list.WarehouseCode = shippingOrderDetail.WarehouseCode;
            list.Status = 2;
            if (list != null)
            {
                return true;
            }
            return false;
        }

        // 获取入库垛信息
        public TStackingStorage GetStackingStorage(string PalletBarcode)
        {
            var list = Context.TStackingStorages
                .Where(x => x.PalletBarcode == PalletBarcode)
                .FirstOrDefault();

            return list;
        }

        // 获取入库垛信息及状态
        public TStackingStorage GetStackingStorageStatus(string PalletBarcode, int status)
        {
            var list = Context.TStackingStorages
                .Where(x => x.PalletBarcode == PalletBarcode && x.Status == status)
                .FirstOrDefault();

            return list;
        }

        // 获取仓位信息
        public TCell GetInventoryByTCell(string palletBarcode)
        {
            TInventory inventoryModel = GetInventory(palletBarcode);

            if (inventoryModel == null)
            {
                return null;
            }

            var cell = Context.TCells.Where(x => x.Code == inventoryModel.LocationCode).FirstOrDefault();
            return cell;

        }

        // 更新仓位信息
        public bool UpdateCell(TCell tcell)
        {
            try
            {
                if (tcell == null)
                {
                    return false;
                }
                tcell.FullStatus = 0;
                tcell.IsLock = false;
                tcell.BusinessType = 0;
                tcell.ModifyDate = DateTime.Now;
                tcell.Status = 1;

                return true;
            }
            catch
            {
                return false;
            }

        }

        // 更新垛主表的状态为失效状态
        public bool UpdateStackingStorage(TStackingStorage model)
        {
            var list = Context.TStackingStorages
                .Where(x => x.Id == model.Id)
                .FirstOrDefault();

            if (list == null)
            {
                return false;
            }
            list.Status = 0;
            list.ModifyDate = DateTime.Now;
            return true;
        }

        // 删除库存表数据
        public bool DeleteInventory(int id)
        {
            try
            {
                var list = Context.TInventories.FirstOrDefault(x => x.Id == id);
                if (list == null)
                {
                    return false;
                }
                Context.TInventories.Remove(list);
                Context.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region 执行出库单
        /// <summary>
        /// 执行出库单
        /// </summary>
        /// <param name="opUser"></param>
        /// <param name="id"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool RunShippingOrderDetail(int id, TShippingOrderDetail shippingOrderDetail, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    if (id <= 0)
                    {
                        message = "请求参数有误，请检查请求参数";
                        return false;
                    }
                    bool result = false;


                    var list = GetInstructsCount(new InstructCriteriaModel
                    {
                        //WarehouseCode = shippingOrderDetail.WarehouseCode,
                        Status = 2,
                    }, shippingOrderDetail);

                    if (list.Count > 0)
                    {
                        message = "存在盘点任务未完成";
                        tran.Rollback();
                        return false;
                    }
                    //if (UpdStatus(shippingOrderDetail.MaterialId) <= 0)
                    //{
                    //    message = "更新库存状态失败";
                    //    tran.Rollback();
                    //    return false;
                    //}
                    TShippingOrderDetail shippingOrderDetailModel = GetShippingOrderDetail(id);
                    shippingOrderDetailModel.Status = (int)EmBillStatus.Executing;
                    shippingOrderDetailModel.ModifyDate = DateTime.Now;
                    shippingOrderDetailModel.ModifyUserId = shippingOrderDetail.CreateUserId;
                    shippingOrderDetailModel.ModifyUserName = shippingOrderDetail.ModifyUserName;


                    //if (ValidScheduledTaskData(shippingOrderDetail.Id))
                    //{
                    //   tran.Rollback();
                    //    return false;
                    // }

                    result = InsertScheduledTask(new TScheduledTask
                    {
                        RecordType = 2,
                        RecordId = shippingOrderDetail.Id,
                        WarehouseId = shippingOrderDetail.WarehouseId,
                        //WarehouseName = shippingOrderDetail.WarehouseName,
                        //WarehouseCode = shippingOrderDetail.WarehouseCode,
                        Priority = (shippingOrderDetail.IsOnceOut.HasValue && shippingOrderDetail.IsOnceOut.Value) ? 999 : 0,
                        RefId = null,
                        Data = null,
                        Status = 0,
                        Title = "出库任务启动",
                        CreateDate = DateTime.Now,
                        CreateUserId = shippingOrderDetail.CreateUserId,
                        CreateUserName = shippingOrderDetail.CreateUserName,
                    }) > 0;
                    if (!result)
                    {
                        message = "出库任务启动失败";
                        tran.Rollback();
                        return false;
                    }

                    result = InsertLog(new TLog
                    {
                        LogType = 1,
                        ActionType = 0,
                        RecordType = 2,
                        RecordId = id,
                        Status = 1,
                        CreateDate = DateTime.Now,
                        UserId = shippingOrderDetail.CreateUserId,
                        UserName = shippingOrderDetail.CreateUserName,
                        RealName = shippingOrderDetail.ModifyUserName,
                        ModuleName = "出库单",
                        Description = shippingOrderDetail.ModifyUserName + "执行了出库单" + shippingOrderDetail.OrderSn
                    }) > 0;
                    if (!result)
                    {
                        message = "保存失败";
                        tran.Rollback();
                        return false;
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return false;
                }
            }

        }

        #endregion


        #region 出库复核
        /// <summary>
        /// 出库复核
        /// </summary>
        /// <param name="OrderDTO"></param>
        /// <returns></returns>
        public bool SubmitOutInventoryReview(SubmitOutListDTO OrderDTO, out string message)
        {
            message = "";
            //message = "";
            //try
            //{
            //    if (OrderDTO.orderDetId <= 0)
            //    {
            //        message = "参数传入错误";
            //        return false;
            //    }

            //    bool result = false;
            //    {
            //        TShippingOrderDetail shippingOrderDetail = GetShippingOrderDetail(OrderDTO.orderDetId);
            //        #region 岳哲
            //        //找出出库要出托盘
            //        var lcokCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == OrderDTO.orderDetId && s.PalletBarcode == OrderDTO.palletBarcode[0]).FirstOrDefault();
            //        if (lcokCell == null)
            //        {
            //            message = "托盘查询失败";
            //            return false;
            //        }
            //        var lockCellPalletBarCode = new List<string>
            //        {
            //            lcokCell.PalletBarcode
            //        };
            //        var inv = Context.TInventory.Find(lcokCell?.InventoryId);
            //        //如果出库数量大于库存数量 不行  
            //        if (OrderDTO.qty > inv?.AvailableQty)
            //        {
            //            message = "出库数量大于预期数量";
            //            return false;
            //        }
            //        //校验所有的出库推盘
            //        foreach (var item in OrderDTO.palletBarcode)
            //        {
            //            if (!lockCellPalletBarCode.Contains(item))
            //            {
            //                message = "出库托盘校验失败";
            //                return false;
            //            }
            //        }

            //        #endregion

            //        var updShippingOrderDetail = UpdInstructsCount(shippingOrderDetail);
            //        if (!updShippingOrderDetail)
            //        {
            //            message = "更新库房信息失败";
            //            return false;
            //        }
            //        int logId = InsertLog(new TLog
            //        {
            //            LogType = 1,
            //            ActionType = 0,
            //            RecordType = 0,
            //            RecordId = OrderDTO.orderDetId,
            //            Status = 1,
            //            CreateDate = DateTime.Now,
            //            UserId = OrderDTO.createUserld,
            //            UserName = OrderDTO.createUser,
            //            RealName = OrderDTO.nowUserRealName,
            //            ModuleName = "出库复核",
            //            Description = string.Format("出库复核【{0}】,数量【{1}】，操作人{2}", shippingOrderDetail.WarehouseName, shippingOrderDetail.Qty, OrderDTO.nowUserRealName),
            //        });
            //        result = logId > 0;
            //        if (!result)
            //        {
            //            message = "出库复核失败";
            //            return false;
            //        }

            //        // 往库存流水表添加数据
            //        if (!AddInventoryFlow(OrderDTO))
            //        {
            //            message = "库存流水信息插入失败";
            //            return false;
            //        }

            //        //更新复核状态
            //        result = UpdateShippingOrderDetail(OrderDTO.orderDetId);
            //        if (!result)
            //        {
            //            message = "更新复核状态失败";
            //            return false;
            //        }
            //        return true;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    return false;
            //}
            return false;
        }

        #endregion

        #region 出库复核Plus

        /// <summary>
        /// 出库复核Plus
        /// </summary>
        /// <param name="OrderDTO"></param>
        /// <returns></returns>
        public bool SubmitOutInventoryReviewPlus(SubmitOutListDTO OrderDTO, out string message)
        {
            //message = "";
            //try
            //{
            //    if (OrderDTO.orderDetId <= 0)
            //    {
            //        message = "参数传入错误";
            //        return false;
            //    }

            //    bool result = false;
            //    {
            //        TShippingOrderDetail shippingOrderDetail = GetShippingOrderDetail(OrderDTO.orderDetId);
            //        #region 岳哲
            //        //找出出库要出托盘
            //        var lcokCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == OrderDTO.orderDetId).FirstOrDefault();
            //        if (lcokCell == null)
            //        {
            //            message = "托盘查询失败";
            //            return false;
            //        }
            //        var lockCellPalletBarCode = new List<string>();
            //        foreach (string palletBarcode in OrderDTO.palletBarcode)
            //        {
            //            lockCellPalletBarCode.Add(palletBarcode);
            //        }
            //        var inv = Context.TInventory.Find(lcokCell?.InventoryId);
            //        //如果出库数量大于库存数量 不行  
            //        if (OrderDTO.qty > inv?.AvailableQty)
            //        {
            //            message = "出库数量大于预期数量";
            //            return false;
            //        }
            //        //校验所有的出库推盘
            //        foreach (var item in OrderDTO.palletBarcode)
            //        {
            //            if (!lockCellPalletBarCode.Contains(item))
            //            {
            //                message = "出库托盘校验失败";
            //                return false;
            //            }
            //        }

            //        #endregion

            //        var updShippingOrderDetail = UpdInstructsCount(shippingOrderDetail);
            //        if (!updShippingOrderDetail)
            //        {
            //            message = "更新库房信息失败";
            //            return false;
            //        }
            //        int logId = InsertLog(new TLog
            //        {
            //            LogType = 1,
            //            ActionType = 0,
            //            RecordType = 0,
            //            RecordId = OrderDTO.orderDetId,
            //            Status = 1,
            //            CreateDate = DateTime.Now,
            //            UserId = OrderDTO.createUserld,
            //            UserName = OrderDTO.createUser,
            //            RealName = OrderDTO.nowUserRealName,
            //            ModuleName = "出库复核",
            //            Description = string.Format("出库复核【{0}】,数量【{1}】，操作人{2}", shippingOrderDetail.WarehouseName, shippingOrderDetail.Qty, OrderDTO.nowUserRealName),
            //        });
            //        result = logId > 0;
            //        if (!result)
            //        {
            //            message = "插入出库复核日志失败";
            //            return false;
            //        }
            //        //更新复核状态
            //        result = UpdateShippingOrderDetail(OrderDTO.orderDetId);
            //        if (!result)
            //        {
            //            message = "更新复核状态失败";
            //            return false;
            //        }
            //        return true;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    return false;
            //}
            message = "";
            return false;
        }

        #endregion

        #region 出库解绑
        /// <summary>
        /// 出库解绑
        /// </summary>
        /// <param name="palletBarcode"></param>
        /// <param name="user"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool HandleUnbindOfOutstorage(SubmitOutListDTO OrderDTO, out string message)
        {
            //message = "";
            //try
            //{
            //    bool result = false;

            //    foreach (var palletBarcode in OrderDTO.palletBarcode)
            //    {
            //        var pall = Context.TStackingStorages.Where(x => x.PalletBarcode == palletBarcode).FirstOrDefault();
            //        if (pall == null)
            //        {
            //            message = "垛条码信息查询失败";
            //            return false;
            //        }
            //        TStackingStorage model = this.GetStackingStorageStatus(palletBarcode, pall.Status);
            //        if (model == null)
            //        {
            //            message = "获取垛条码信息失败";
            //            return false;
            //        }
            //        TInventory inventoryModel = GetInventory(palletBarcode);
            //        if (inventoryModel == null)
            //        {
            //            message = "获取库存信息失败";
            //            return false;
            //        }

            //        var tcell = GetInventoryByTCell(palletBarcode);
            //        result = UpdateCell(tcell);
            //        if (!result)
            //        {
            //            message = "获取仓位信息";
            //            return false;
            //        }

            //        result = UpdateStackingStorage(model);
            //        if (!result)
            //        {
            //            message = "更新垛条码信息失败";
            //            return false;
            //        }

            //        var inventoryOrder = GetTInventoryId(palletBarcode);

            //        // 获取库存数量
            //        var qty = GetInventoryQuantity(inventoryOrder.MaterialId);

            //        if (qty < 0)
            //        {
            //            message = "获取库存数量失败";
            //            return false;
            //        }

            //        // 库存数量减去需要出库的数量
            //        if (inventoryOrder.AvailableQty - OrderDTO.qty == 0)
            //        {
            //            result = DeleteInventory(inventoryModel.Id);
            //            if (!result)
            //            {
            //                message = "删除库存信息失败";
            //                return false;
            //            }
            //            // 如果出完库就修改仓位锁定表数据 
            //            if (!UpdTShippingLockCell(OrderDTO.orderDetId, OrderDTO.palletBarcode[0]))
            //            {
            //                return false;
            //            }
            //        }
            //        else
            //        {
            //            // 减去库存数量并修改库存状态
            //            if (!GetDwindleNumbers(inventoryOrder, OrderDTO.qty))
            //            {
            //                message = "修改库存状态失败";
            //                return false;
            //            }
            //            // 如果没有出完库就更新仓位锁定表中的库存数量
            //            var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == OrderDTO.orderDetId && s.PalletBarcode == OrderDTO.palletBarcode[0]).FirstOrDefault();
            //            if (lockCell != null)
            //            {
            //                lockCell.InventoryQty -= OrderDTO.qty;
            //                Context.TShippingLockCells.Update(lockCell);
            //                Context.SaveChanges();
            //            }
            //        }

            //    }
            //    // 出库单数量修改 状态修改
            //    var shippingOrderDetail = Context.TShippingOrderDetails.Find(OrderDTO.orderDetId);
            //    if (shippingOrderDetail != null)
            //    {
            //        shippingOrderDetail.ShippedQty += OrderDTO.qty;
            //        if (shippingOrderDetail.ShippedQty == shippingOrderDetail.Qty)
            //        {
            //            shippingOrderDetail.Status = 4;
            //        }


            //        //TShippingGoodsDetail shippingGoods = Context.TShippingGoodsDetails.Where(s => s.OrderDetailId == OrderDTO.orderDetId).FirstOrDefault();
            //        //if (shippingGoods == null)
            //        //{
            //        //    message = "找不到出库单货品明细";
            //        //    return false;
            //        //}
            //        //shippingGoods.Status = 1;
            //        //Context.TShippingGoodsDetails.Update(shippingGoods);
            //        Context.SaveChanges();
            //    }
            //    else
            //    {
            //        message = "出库单状态修改失败";
            //        return false;
            //    }

            //    int logId = InsertLog(new TLog
            //    {
            //        LogType = 1,
            //        ActionType = 7,
            //        Status = 1,
            //        CreateDate = DateTime.Now,
            //        UserId = OrderDTO.createUserld,
            //        UserName = OrderDTO.nowUserRealName,
            //        RealName = OrderDTO.nowUserRealName,
            //        //ModuleName = model.ModuleName,
            //        Description = "出库解绑成功",
            //    });
            //    result = logId > 0;
            //    if (!result)
            //    {
            //        message = "出库解绑失败";
            //        return false;
            //    }

            //    return true;
            //}
            //catch (Exception ex)
            //{
            //    throw;
            //}
            message = ""
;            return false;
        }

        #endregion


        #region 出库解绑Plus

        /// <summary>
        /// 出库解绑Plus
        /// </summary>
        /// <param name="palletBarcode"></param>
        /// <param name="user"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool HandleUnbindOfOutstoragePlus(SubmitOutListDTO OrderDTO, out string message)
        {
            message = "";
            try
            {
                bool result = false;

                foreach (var palletBarcode in OrderDTO.palletBarcode)
                {
                    var pall = Context.TStackingStorages.Where(x => x.PalletBarcode == palletBarcode).FirstOrDefault();
                    if (pall == null)
                    {
                        message = "垛条码信息查询失败";
                        return false;
                    }
                    TStackingStorage model = this.GetStackingStorageStatus(palletBarcode, pall.Status);
                    if (model == null)
                    {
                        message = "获取垛条码信息失败";
                        return false;
                    }
                    TInventory inventoryModel = GetInventory(palletBarcode);
                    if (inventoryModel == null)
                    {
                        message = "获取库存信息失败";
                        return false;
                    }

                    var tcell = GetInventoryByTCell(palletBarcode);
                    result = UpdateCell(tcell);
                    if (!result)
                    {
                        message = "获取仓位信息";
                        return false;
                    }

                    result = UpdateStackingStorage(model);
                    if (!result)
                    {
                        message = "更新垛条码信息失败";
                        return false;
                    }

                    var inventoryOrder = GetTInventoryId(palletBarcode);

                    // 获取库存数量
                    var qty = GetInventoryQuantity(inventoryOrder.MaterialId);

                    if (qty < 0)
                    {
                        message = "获取库存数量失败";
                        return false;
                    }

                    // 库存数量减去需要出库的数量
                    if (inventoryOrder.AvailableQty - OrderDTO.qty == 0)
                    {
                        result = DeleteInventory(inventoryModel.Id);
                        if (!result)
                        {
                            message = "删除库存信息失败";
                            return false;
                        }
                        // 如果出完库就修改仓位锁定表数据 
                        if (!UpdTShippingLockCell(OrderDTO.orderDetId, OrderDTO.palletBarcode[0]))
                        {
                            Context.TLogs.Add(new TLog()
                            {
                                ActionType = 4,
                                CreateDate = DateTime.Now,
                                Description = "仓位修改表修改状态失败，托盘：" + OrderDTO.palletBarcode[0],
                                LogType = 1,
                                ModuleName = "PDA出库",
                            });
                            return false;
                        }


                        // 往库存流水表添加数据
                        CreateTInventoryLogs(OrderDTO);


                    }
                    else
                    {
                        // 减去库存数量并修改库存状态
                        if (!GetDwindleNumbers(inventoryOrder, OrderDTO.qty))
                        {
                            message = "修改库存状态失败";
                            return false;
                        }
                        // 如果没有出完库就更新仓位锁定表中的库存数量
                        var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == OrderDTO.orderDetId).FirstOrDefault();
                        if (lockCell != null)
                            lockCell.InventoryQty -= OrderDTO.qty;

                        CreateTInventoryLogs(OrderDTO);

                    }

                    // 出库单数量修改 状态修改
                    var shippingOrderDetail = Context.TShippingOrderDetails.Find(OrderDTO.orderDetId);
                    //if (shippingOrderDetail != null)
                    //{
                    //    shippingOrderDetail.ShippedQty += OrderDTO.qty;
                    //    if (shippingOrderDetail.ShippedQty == shippingOrderDetail.Qty)
                    //    {
                    //        shippingOrderDetail.Status = 4;
                    //    }

                    //    //TShippingGoodsDetail shippingGoods = Context.TShippingGoodsDetails.Where(s => s.OrderDetailId == OrderDTO.orderDetId && s.PalletBarcode == OrderDTO.palletBarcode[0]).FirstOrDefault();
                    //    //if (shippingGoods == null)
                    //    //{
                    //    //    return false;
                    //    //}
                    //    //shippingGoods.Status = 1;
                    //    //Context.TShippingGoodsDetails.Update(shippingGoods);
                    //    Context.SaveChanges();
                    //}
                    //else
                    //{
                    //    message = "出库单状态修改失败";
                    //    return false;
                    //}

                    int logId = InsertLog(new TLog
                    {
                        LogType = 1,
                        ActionType = 7,
                        Status = 1,
                        CreateDate = DateTime.Now,
                        UserId = OrderDTO.createUserld,
                        UserName = OrderDTO.nowUserRealName,
                        RealName = OrderDTO.nowUserRealName,
                        //ModuleName = model.ModuleName,
                        Description = "出库解绑成功",
                    });
                    result = logId > 0;
                    if (!result)
                    {
                        message = "出库解绑失败";
                        return false;
                    }
                }


                return true;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 库存流水添加数据
        /// </summary>
        /// <param name="OrderDetailId"></param>
        /// <returns></returns>
        public bool CreateTInventoryLogs(SubmitOutListDTO OrderDTO)
        {
            var orderDetail = Context.TShippingOrderDetails.Where(s => s.Id == OrderDTO.orderDetId).FirstOrDefault();
            var lockCell = Context.TShippingLockCells.Where(s => s.PalletBarcode == OrderDTO.palletBarcode[0]).FirstOrDefault();
            var inventoryLog = new TInventoryLog
            {
                SourceType = 1,
                SourceSn = orderDetail?.OrderSn,
                WarehouseId = orderDetail?.WarehouseId,
                //WarehouseName = orderDetail?.WarehouseName,
                LocationCode = lockCell?.CellCode,
                PalletBarcode = OrderDTO.palletBarcode[0],

                MaterialId = lockCell?.MaterialId,
                MaterialCode = lockCell?.MaterialCode,
                MaterialName = lockCell?.MaterialName,
                StartQty = lockCell?.InventoryQty,
                ChangeQty = OrderDTO.qty,
                EndQty = lockCell?.InventoryQty - OrderDTO.qty, //使用库存数量减去实际出库数量 等于最终数量
                //BaseUnitId = orderDetail?.UnitId,
                //BaseUnitName = orderDetail?.UnitName,
                Remark = "",
                CreateDate = DateTime.Now,
                CreateUserId = OrderDTO.createUserld,
                CreateUser = OrderDTO.createUser
            };
            Context.TInventoryLog.Add(inventoryLog);
            if (Context.SaveChanges() <= 0)
            {
                Context.TLogs.Add(new TLog()
                {
                    ActionType = 4,
                    CreateDate = DateTime.Now,
                    Description = "库存流水添加失败，托盘：" + OrderDTO.palletBarcode[0],
                    LogType = 1,
                    ModuleName = "PDA出库",
                });
                return false;
            }
            return true;
        }

        #endregion

        // 查询托盘条码,并根据托盘条码查询其他信息
        public List<CreateOutboundOrderDTO> GetPalletBarcodePDA(int OrderDetailId)
        {
            var lockCellList = Context.TShippingLockCells.Where(x => x.OrderDetailId == OrderDetailId).Select(s => new CreateOutboundOrderDTO()
            {
                DeliveryOrderID = s.OrderDetailId,
                CellCode = s.CellCode,
                PalletBarcode = s.PalletBarcode,
                MaterialsId = s.MaterialId.GetValueOrDefault(),
                MaterialCode = s.MaterialCode,
                InventoryQty = s.InventoryQty.GetValueOrDefault(),
                OutQty = s.OutQty.GetValueOrDefault()
            });

            List<CreateOutboundOrderDTO> Outbound = lockCellList.ToList();
            return Outbound;
        }


        // 根据垛条码查询库存ID
        public TInventory GetTInventoryId(string palletBarcode)
        {
            var list = Context.TInventory
                .Where(x => x.PalletBarcode == palletBarcode)
                .FirstOrDefault();

            return list;
        }

        /// <summary>
        /// 修改仓位锁定状态
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        public bool UpdTShippingLockCell(int OrderId,string palletBarCode)
        {
            try
            {
                var list = Context.TShippingLockCells
               .FirstOrDefault(x => x.OrderDetailId == OrderId && x.PalletBarcode== palletBarCode);
                if (list == null)
                {
                    return false;
                }
                list.IsPicking = true;
                Context.TShippingLockCells.Update(list);
                Context.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }


        }


        /// <summary>
        /// 查询出库单相关信息
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        public List<CreateOutboundOrderDTO> GetOutboundOrder(string PalletBarcode)
        {
            var list = (
                        from shippingOrder in Context.TShippingOrderDetails
                        join inventory in Context.TInventories on shippingOrder.PalletBarcode equals inventory.PalletBarcode
                        where shippingOrder.PalletBarcode == PalletBarcode
                        select new CreateOutboundOrderDTO
                        {
                            DeliveryOrderID = shippingOrder.Id,
                            WareHouseId = (int)shippingOrder.WarehouseId,
                            //MaterialsId = shippingOrder.MaterialId,
                            InventoryId = inventory.Id,
                            CellCode = inventory.LocationCode,

                        }
                    ).ToList();

            return list;
        }


        /// <summary>
        /// 获取出库单状态为0数据
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllShippingOrderSn()
        {
            List<string> OrderSnList = new List<string>();
            var list = Context.TShippingOrderDetails.Where(x => x.Status == 2).ToList();
            foreach ( var shippingOrder in list )
            {
                string OrderSn = shippingOrder.OrderSn;
                OrderSnList.Add(OrderSn);
            }
            OrderSnList = OrderSnList.OrderByDescending(x => x).ToList();

            return OrderSnList;
        }

        /// <summary>
        /// 根据单号查询信息
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        public ShippingLockCellDto GetShippingByOrderSn(string OrderSn)
        {
            ShippingLockCellDto shippingLockCell = new ShippingLockCellDto();

            var shippingOrderList = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();
            if (shippingOrderList == null || shippingOrderList.Count == 0)
            {
                return null;
            }
            shippingLockCell.OrderSn = OrderSn;
            var lockCellList = Context.TShippingLockCells.Where(x => x.OrderDetailId == shippingOrderList.First().Id).ToList();

            shippingLockCell.shippingLockCells = lockCellList;

            return shippingLockCell;
        }

        /// <summary>
        /// 更新状态（有网）
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool UpdShippingLock(ShippingLockUpdDto dto, out string message)
        {
            message = "";
            using var tran = Context.Database.BeginTransaction();
            try
            {

                TShippingLockCell shippingLockCell = new TShippingLockCell();
                List<GroupShippingOrderDto> dtos = new List<GroupShippingOrderDto>();
                var ShippingList = Context.TShippingOrderDetails.Where(x => x.OrderSn == dto.OrderSn).ToList();
                if(ShippingList.Count() <= 0)
                {
                    tran.Rollback();
                    message = "暂无此出库单:" + dto.OrderSn;
                    return false;
                }
                var detailListLock = Context.TShippingLockCells.Where(x => x.OrderDetailId == ShippingList.FirstOrDefault().Id).ToList();
                var cellList = Context.TCells.Where(x => x.Code == dto.CellName).ToList();
                if(cellList.Count() <= 0)
                {
                    tran.Rollback();
                    message = "暂无仓位" + dto.OutCellName;
                    return false;
                }
                var inventoryList = Context.TInventories.Where(x => x.LocationCode == dto.CellName && x.MaterialName == dto.MaterialName).ToList();
                if(inventoryList.Count() <= 0)
                {
                    tran.Rollback();
                    message = "暂无库存";
                    return false;
                }
                var materailList = Context.TMaterial.Where(x => x.Code == inventoryList.FirstOrDefault().MaterialCode).ToList();
                if(materailList.Count() <= 0)
                {
                    tran.Rollback();
                    message = "暂无物料" + dto.MaterialName;
                    return false;
                }

                if(detailListLock.Count <= 0)
                {
                    TShippingLockCell shippingLockCell1 = new TShippingLockCell();
                    var detail = Context.TShippingOrderDetails.Where(x => x.OrderSn == dto.OrderSn);
                    shippingLockCell.OrderDetailId = detail.FirstOrDefault().Id;
                    shippingLockCell.OutQty = dto.OutQty;
                    shippingLockCell.InventoryQty = dto.InventoryQty;
                    shippingLockCell.CellId = cellList.FirstOrDefault().Id;
                    shippingLockCell.CellCode = cellList.FirstOrDefault().Code;
                    shippingLockCell.CellName = cellList.FirstOrDefault().Name;
                    shippingLockCell.MaterialCategoryId = dto.MaterialCategoryId;
                    shippingLockCell.MaterialCategoryCode = dto.MaterialCategoryCode;
                    shippingLockCell.MaterialCategoryName = dto.MaterialCategoryName;
                    shippingLockCell.MaterialId = inventoryList.FirstOrDefault().Id;
                    shippingLockCell.MaterialCode = inventoryList.FirstOrDefault().MaterialCode;
                    shippingLockCell.MaterialName = dto.MaterialName;
                    shippingLockCell.CreateDate = DateTime.Now;
                    shippingLockCell.ModelSpec = materailList.FirstOrDefault().ModelSpec;
                    shippingLockCell.QualityState = materailList.FirstOrDefault().QualityState;
                    shippingLockCell.UnitId = materailList.FirstOrDefault().UnitId;
                    shippingLockCell.UnitName = materailList.FirstOrDefault().UnitName;
                    shippingLockCell.Price = materailList.FirstOrDefault().Price;
                    shippingLockCell.TotalPrice = dto.OutQty * materailList.FirstOrDefault().Price;
                    Context.TShippingLockCells.Add(shippingLockCell);
                    if(Context.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        message = "添加出库单明细失败";
                        return false;
                    }


                }
                int y = 0;
                GroupShippingOrderDto groupShippingOrderDto = new GroupShippingOrderDto();
                foreach (var item in ShippingList)
                {
                    if (item.Status != 2)
                    {
                        message = "单号" + dto.OrderSn + "状态不正确，请查看是否审批或完成";
                    }
                    item.Status = 4;
                    Context.TShippingOrderDetails.Update(item);
                    
                    if (Context.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        message = "修改出库单状态失败";
                        return false;
                    }
                    if (dto.MaterialCode == "undefined")
                    {
                        var InventoryList = Context.TInventories.Where(x => x.MaterialCode == dto.MaterialCode);
                        var MaterialListAll = Context.TMaterial.Where(x => x.Code == dto.MaterialCode);
                        if (MaterialListAll.Count() <= 0)
                        {
                            message = "请求物料编码有误";
                            tran.Rollback();
                            return false;
                        }
                        var MaterialList = MaterialListAll.First(x => x.Code == dto.MaterialCode);
                        TShippingLockCell shippingLockCell1 = new TShippingLockCell();
                        shippingLockCell.OrderDetailId = Context.TShippingOrderDetails.First(x => x.OrderSn == dto.OrderSn).Id;
                        shippingLockCell.OutQty = dto.OutQty;
                        shippingLockCell.InventoryQty = InventoryList.Count(x => x.AvailableQty != 0);
                        shippingLockCell.MaterialId = MaterialList.Id;
                        shippingLockCell.MaterialCode = MaterialList.Code;
                        shippingLockCell.MaterialName = dto.MaterialName;
                        shippingLockCell.MaterialCategoryId = MaterialList.MaterialCategoryId;
                        shippingLockCell.MaterialCategoryCode = MaterialList.MaterialCategoryCode;
                        shippingLockCell.MaterialCategoryName = MaterialList.MaterialCategoryName;
                        shippingLockCell.UnitId = MaterialList.UnitId;
                        shippingLockCell.UnitName = MaterialList.UnitName;
                        shippingLockCell.ModelSpec = MaterialList.ModelSpec;
                        shippingLockCell.QualityState = MaterialList.QualityState;
                        shippingLockCell.Price = InventoryList.First(x => x.MaterialCode == MaterialList.Code).Price;
                        shippingLockCell.TotalPrice = dto.OutQty * shippingLockCell.Price;
                        shippingLockCell.MaterialGroupCode = MaterialList.MaterialGroupCode;
                        Context.TShippingLockCells.Add(shippingLockCell);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "添加出库明细失败";
                            tran.Rollback();
                            return false;
                        }
                       
                    }
                    var ShippingLock = Context.TShippingLockCells.Where(x => x.OrderDetailId == item.Id && x.MaterialName == dto.MaterialName).ToList();
                    groupShippingOrderDto.BillType = item.BillType;
                    groupShippingOrderDto.Agent = item.Agent;
                    groupShippingOrderDto.SupplierId = item.SupplierId;
                    groupShippingOrderDto.SupplierCode = item.SupplierCode;
                    groupShippingOrderDto.SupplierName = item.SupplierName;
                    groupShippingOrderDto.Contact = item.Contact;
                    groupShippingOrderDto.ContactMobile = item.ContactMobile;
                    groupShippingOrderDto.ProductDate = item.CreateDate;
                    groupShippingOrderDto.Remark = item.Remark;
                    groupShippingOrderDto.NowUserId = item.NowUserId;
                    groupShippingOrderDto.NowUserName = item.NowUserRealName;
                    groupShippingOrderDto.shippingLockCells.Add(shippingLockCell);
                    dtos.Add(groupShippingOrderDto);
                    // ;

                  
                }
                foreach (var item in dtos)
                {
                    // 减库存
                    var TInventoryList = Context.TInventory.Where(x => x.LocationCode == dto.CellName && x.MaterialName == dto.MaterialName).ToList();
                    if (TInventoryList.Count() <= 0)
                    {
                        tran.Rollback();
                        message = "未查询到出库单中添加的物料! 物料编码:" + TInventoryList[0].MaterialCode;
                        return false;
                    }
                    TInventoryLog inventory = new TInventoryLog();
                    inventory.SourceType = 1;
                    inventory.SourceSn = dto.OrderSn;
                    inventory.WarehouseId = TInventoryList[0].WarehouseId;
                    inventory.WarehouseName = TInventoryList[0].WarehouseName;
                    inventory.LocationCode = TInventoryList[0].LocationCode;
                    inventory.PalletBarcode = TInventoryList[0].PalletBarcode;
                    inventory.MaterialId = TInventoryList[0].MaterialId;
                    inventory.MaterialCode = TInventoryList[0].MaterialCode;
                    inventory.MaterialName = TInventoryList[0].MaterialName;
                    inventory.BaseUnitId = TInventoryList[0].UnitId;
                    inventory.BaseUnitName = TInventoryList[0].UnitName;
                    //原始数量
                    inventory.StartQty = TInventoryList[0].AvailableQty;
                    //变更数量
                    inventory.ChangeQty = dto.OutQty;
                    TInventoryList[0].AvailableQty = TInventoryList[0].AvailableQty -= dto.OutQty;
                    //最终数量
                    inventory.EndQty = inventory.StartQty - dto.OutQty;
                    inventory.CreateDate = DateTime.Now;
                    inventory.CreateUserId = item.CreateUserId;
                    inventory.CreateUser = item.CreateUserName;
                    //var WarningRolesList = Context.TWarningRules.First(x => x.MaterialCode == TInventoryList[0].MaterialCode);
                    //if (TInventoryList[0].AvailableQty < WarningRolesList.WarningQtyMin)
                    //{
                    //    TInventoryWarn inventoryWarnModel = new TInventoryWarn();
                    //    inventoryWarnModel.MaterialId = TInventoryList[0].MaterialId;
                    //    inventoryWarnModel.MaterialCode = TInventoryList[0].MaterialCode;
                    //    inventoryWarnModel.MaterialName = TInventoryList[0].MaterialName;
                    //    inventoryWarnModel.MaterialTypeName = TInventoryList[0].MaterialTypeName;
                    //    inventoryWarnModel.WarnType = 1;
                    //    inventoryWarnModel.QTY = TInventoryList[0].AvailableQty;
                    //    Context.TInventoryWarn.Add(inventoryWarnModel);
                    //}

                    _tShippingOrderDetailRepository.IsInventoryWarn(TInventoryList);

                    Context.TInventoryLogs.Add(inventory);
                    if (TInventoryList[0].AvailableQty <= 0)
                    {
                        Context.TInventories.Remove(TInventoryList[0]);
                        var MaterialList = Context.TMaterial.First(x => x.Code == inventory.MaterialCode);
                        Context.TMaterial.Remove(MaterialList);
                    }

                    var ShippingOrderDetailList = Context.TShippingOrderDetails.FirstOrDefault(x => x.OrderSn == dto.OrderSn);
                    if (ShippingOrderDetailList == null)
                    {
                        tran.Rollback();
                        message = "出库单明细不存在! 单号:" + item.OrderSn;
                        return false;
                    }

                }

                if (Context.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    message = "出库减去库存失败！";
                    return false;
                }
                tran.Commit();
                message = "出库减去库存成功！";
                return true;


            }
            catch
            {
                tran.Rollback();
                message = "更新数据失败";
                return false;
            }
           

        }

        /// <summary>
        /// 获取此巷道是不是最后一个
        /// </summary>
        /// <param name="cellCode"></param>
        /// <returns></returns>
        public bool GetTemporary(out int status,string cellCode)
        {
            status = 0;
            var temporaryList = Context.TTemporaryTable.AsQueryable();
            var newList = temporaryList.Where(x => x.CellCode == cellCode);
            string routerwayCode = temporaryList.FirstOrDefault().RoutewayCode;
            int count = temporaryList.Where(x => x.RoutewayCode == routerwayCode).Count();

            if (count < 0)
            {
                status = 1;
                return true;
            }

            foreach (var item in newList)
            {
                Context.TTemporaryTable.Remove(item);
                if(Context.SaveChanges() <= 0)
                {
                    return false;
                }

            }
            return true;
        }



        /// <summary>
        /// 根据物料编码查询其他信息
        /// </summary>
        /// <param name="MaterialCode"></param>
        /// <returns></returns>
        public ShippingByMaterialCodeDto GetShippingByMaterialCode(out string message,string MaterialCode)
        {
            message = "";
            ShippingByMaterialCodeDto shippingByMaterialCodeDto = new ShippingByMaterialCodeDto();
            var inventoryList = Context.TInventories.Where(x => x.MaterialCode == MaterialCode).ToList();
            if(inventoryList.Count() <= 0)
            {
                message = "暂无此库存信息";
                return null;
            }
            shippingByMaterialCodeDto.MaterialCategoryId = inventoryList[0].MaterialCategoryId;
            shippingByMaterialCodeDto.MaterialCategoryCode = inventoryList[0].MaterialCategoryCode;
            shippingByMaterialCodeDto.MaterialCategoryName = inventoryList[0].MaterialCategoryName;
            shippingByMaterialCodeDto.MaterialId = inventoryList[0].MaterialId;
            shippingByMaterialCodeDto.MaterialCode = inventoryList[0].MaterialCode;
            shippingByMaterialCodeDto.MaterialName = inventoryList[0].MaterialName;
            shippingByMaterialCodeDto.QualityState = inventoryList[0].QualityState;
            List<string> cellList = new List<string>();
            foreach (var item in inventoryList)
            {
                if(item.LocationCode == null )
                {
                    message = "该物料暂无仓位";
                    return null;
                }
                string cellCode = item.LocationCode;
                cellList.Add(cellCode);
            }
            shippingByMaterialCodeDto.LocationCode = cellList;


            return shippingByMaterialCodeDto;
        }

        /// <summary>
        /// 根据仓位查库存数量
        /// </summary>
        /// <param name="CellCode"></param>
        /// <returns></returns>
        public decimal? GetQtyByCellCode(string locationCode)
        {
            var inventoryList = Context.TInventories.Where(x => x.LocationCode.Equals(locationCode)).ToList();
            if(inventoryList.Count == 0)
            {
                return 0;
            }
            return inventoryList[0].AvailableQty;
        }
    }


}
